package com.pub.paypal.common.operation;


import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import com.pub.paypal.common.util.PayPalClient;
import com.pub.paypal.config.PaypalConfig;
import com.pub.paypal.model.CreateOrderEntity;
import com.pub.paypal.model.PayPalCheckoutConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component
public class CreateOrder {

    /**
     * 生成订单主体信息
     */
    private OrderRequest buildRequestBody(CreateOrderEntity createOrderEntity) {
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.checkoutPaymentIntent(PayPalCheckoutConstant.CAPTURE);
        ApplicationContext applicationContext = new ApplicationContext()
                .brandName(PayPalCheckoutConstant.BRAND_NAME)
                .cancelUrl(PaypalConfig.CANCEL_URL)
                .returnUrl(PaypalConfig.RETURN_URL)
                .userAction(PayPalCheckoutConstant.USERACTION)
                .shippingPreference(PayPalCheckoutConstant.SHIPPINGPREFERENCE);
        orderRequest.applicationContext(applicationContext);
        List<PurchaseUnitRequest> purchaseUnits = new ArrayList<>();
        purchaseUnits.add(new PurchaseUnitRequest()
                        .description(createOrderEntity.getDescription())  //商品名称
                        .customId(createOrderEntity.getCustomId()) // 自定义编号，需要对应本地订单号有迹可循
                        .invoiceId(createOrderEntity.getInvoiceId()) // 本地订单号同上
                        .amountWithBreakdown(new AmountWithBreakdown()
                                .currencyCode(createOrderEntity.getCurrencyCode())  //货币类型
                                .value(String.valueOf(createOrderEntity.getValue()))  //价格
                        ));
        /*purchaseUnits.add(new PurchaseUnitRequest()
                .referenceId("25135623622")  //多个商品时候要求该编号唯一
                .description(createOrderEntity.getDescription() + "test2")  //商品名称
                .customId(createOrderEntity.getCustomId() + "2") // 自定义编号，需要对应本地订单号有迹可循
                .invoiceId(createOrderEntity.getInvoiceId() + "2") // 本地订单号同上
                .amountWithBreakdown(new AmountWithBreakdown()
                        .currencyCode(createOrderEntity.getCurrencyCode())  //货币类型
                        .value(String.valueOf(createOrderEntity.getValue()))  //价格
                ));*/
        /*PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()
                .description("新一代读写一体，智能电子笔记本")
                .customId("P2020052514440001")
                .invoiceId("P2020052514440001")
                .amountWithBreakdown(new AmountWithBreakdown()
                        .currencyCode("USD")
                        .value("220.00")// value = itemTotal + shipping + handling + taxTotal + shippingDiscount;
                        .amountBreakdown(new AmountBreakdown()
                                .itemTotal(new Money().currencyCode("USD").value("220.00")) // itemTotal = Item[Supernote A6](value × quantity) + Item[帆布封套](value × quantity)
                                .shipping(new Money().currencyCode("USD").value("0.00"))
                                .handling(new Money().currencyCode("USD").value("0.00"))
                                .taxTotal(new Money().currencyCode("USD").value("0.00"))
                                .shippingDiscount(new Money().currencyCode("USD").value("0.00"))))
                .items(new ArrayList<Item>() {
                    {
                        add(new Item().name("Supernote A6").description("丝滑般流畅的书写体验")
                                .unitAmount(new Money()
                                        .currencyCode("USD")
                                        .value("200.00"))
                                .quantity("1"));
                        add(new Item().name("帆布封套").description("黑色帆布保护封套")
                                .unitAmount(new Money()
                                        .currencyCode("USD")
                                        .value("20.00"))
                                .quantity("1"));
                    }
                })
                .shippingDetail(new ShippingDetail()
                        .name(new Name().fullName("RATTA"))
                        .addressPortable(new AddressPortable()
                                .addressLine1("梅陇镇")
                                .addressLine2("集心路168号")
                                .adminArea2("闵行区")
                                .adminArea1("上海市")
                                .postalCode("20000")
                                .countryCode("CN")));
                purchaseUnits.add(purchaseUnitRequest);*/
        orderRequest.purchaseUnits(purchaseUnits);
        return orderRequest;
    }

    /**
     * 创建订单的方法
     * @throws //收银台地址
     */
    public String createOrder(CreateOrderEntity createOrderEntity)  {
        OrdersCreateRequest request = new OrdersCreateRequest();
        request.header("prefer","return=representation");
        request.requestBody(buildRequestBody(createOrderEntity));
        PayPalClient payPalClient = new PayPalClient();

        HttpResponse<Order> response = null;
        try {
            response = payPalClient.client().execute(request);
        } catch (IOException e1) {
            try {
                log.error("第1次调用paypal订单创建失败");
                response = payPalClient.client().execute(request);
            } catch (Exception e) {
                try {
                    log.error("第2次调用paypal订单创建失败");
                    response = payPalClient.client().execute(request);
                } catch (Exception e2) {
                    log.error("第3次调用paypal订单创建失败，失败原因：{}", e2.getMessage());
                }
            }
        }
        String approve = "";
        if (response.statusCode() == 201) {
            log.info("Status Code = {}, Status = {}, OrderID = {}, Intent = {}", response.statusCode(), response.result().status(), response.result().id(), response.result().checkoutPaymentIntent());
            Order order = response.result();
            order.links().forEach(link -> log.info(link.rel() + " => " + link.method() + ":" + link.href()));
            //交易成功后，跳转反馈地址
            for(LinkDescription links : order.links()){
                if(links.rel().equals("approve")){
                    approve = links.href();
                }
            }

        }
        return approve;
    }

}